
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="试卷名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="科目" prop="subject">
            <el-select v-model="queryParams.subject" placeholder="请选择" clearable size="small">
              <el-option
                v-for="dict in subjectList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb10" style="float:right">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="dataList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            header-align="center"
            width="50"
            label="序号"
            fixed="left"
            align="center"
          />
          <el-table-column
            header-align="center"
            prop="name"
            width="200"
            :show-overflow-tooltip="true"
            label="试卷名称"
          />
          <el-table-column header-align="center" prop="subject" label="适用科目" :show-overflow-tooltip="true" />
          <el-table-column label="状态" header-align="center" align="left" prop="status">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === 1 ? 'success' : 'info'"
              >{{ scope.row.status === 1 ? '上架' : '下架' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="免费公开" header-align="center" align="left" prop="is_free_public">
            <template slot-scope="scope">{{ scope.row.is_free_public === 1 ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column label="适用地区" header-align="center" align="left" prop="province" />
          <el-table-column
            header-align="center"
            prop="description"
            label="试卷描述"
            :show-overflow-tooltip="true"
            width="200"
          />
          <el-table-column label="创建时间" align="center" prop="createdAt" width="200">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-row :gutter="10">
                <el-col :span="1.5">
                  <router-link
                    :to="{
                      name: 'PaperTopic',
                      params: {id: scope.row.id },
                    }"
                  >
                    <el-button size="mini" type="text">题目管理</el-button>
                  </router-link>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    size="mini"
                    :disabled="!multiple && single"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                  >修改</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    :disabled="!multiple && single"
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>

      <el-drawer
        ref="drawer"
        :title="title + '试卷'"
        :visible.sync="visible"
        direction="rtl"
        custom-class="demo-drawers"
        @closed="reset"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="试卷名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="适用地区" prop="province">
                <el-select
                  v-model="form.province"
                  remote
                  filterable
                  placeholder="请选择地区"
                  :remote-method="remoteMethod"
                  :loading="selectload"
                  style="width: 100%"
                  @change="selectRegion"
                >
                  <el-option
                    v-for="(item, index) in cityList"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="适用科目" prop="subject">
                <el-select
                  v-model="form.subject"
                  style="width: 100%"
                  placeholder="请选择"
                  size="small"
                >
                  <el-option
                    v-for="dict in subjectOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="考试时长（分）" prop="examination_duration">
                <el-input v-model="form.examination_duration" type="number" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="试卷封面" prop="cover">
                <el-upload
                  :headers="headers"
                  :action="$uploadUrl"
                  list-type="picture-card"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="uploadSuccess"
                  :on-remove="handleRemove"
                >
                  <el-image v-if="form.cover" :src="getMediaUrl(form.cover)" class="upload-image" />
                  <i v-else class="el-icon-plus" />
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="免费公开" prop="is_free_public">
                <el-switch
                  v-model="form.is_free_public"
                  :active-value="1"
                  :inactive-value="2"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="试卷状态" prop="status">
                <el-switch
                  v-model="form.status"
                  :active-value="1"
                  :inactive-value="-1"
                  active-text="上架"
                  inactive-text="下架"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="试卷描述" prop="description">
                <el-input v-model="form.description" :rows="4" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-drawer>
    </template>
  </BasicLayout>
</template>

<script>
import {
  examinationList,
  addExamination,
  updateExamination,
  deleteExamination
} from '@/api/admin/sys-examination'
import {
  examinationOptions,
  publicRangeOptions,
  examinationTypeOption
} from './utils'
import { getSubject, getCity } from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
export default {
  name: 'SysTestPaperManage',
  components: {},
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      visible: false,
      dataList: [],
      form: {
        status: 1,
        subject: null,
        is_free_public: 1
      },
      examinationType: examinationTypeOption,
      typeOption: examinationOptions,
      publicRange: publicRangeOptions,
      subjectOptions: [],
      cityList: [],
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        ex_type: [{ required: true, message: '选择类型', trigger: 'blur' }],
        subject: [{ required: true, message: '选择科目', trigger: 'blur' }],
        public_range: [
          { required: true, message: '选择公开范围', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '选择适用地区', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '上传封面', trigger: 'blur' }],
        examination_duration: [
          { required: true, message: '考试时长', trigger: 'blur' }
        ]
      },
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined,
        type: undefined,
        subject: undefined
      },
      selectload: false,
      subjectList: []
    }
  },
  watch: {
    form: {
      deep: true,
      handler(val) {
        if (val.province) {
          getSubject({ province: val.province }).then(response => {
            this.subjectOptions =
              response?.data?.map(item => ({
                label: item.name,
                value: item.name
              })) || []
          })
        }
      }
    },
    visible: {
      handler(val) {
        if (!val) {
          this.subjectOptions = []
        }
      }
    }
  },
  created() {
    this.getList()
    this.getCityList()
    getSubject().then(response => {
      this.subjectList =
        response?.data?.map(item => ({
          label: item.name,
          value: item.name
        })) || []
    })
  },
  methods: {
    selectRegion(val) {
      this.form.subject = null
      getSubject({ province: val }).then(response => {
        this.subjectOptions =
          response?.data?.map(item => ({
            label: item.name,
            value: item.name
          })) || []
      })
    },
    getCityList() {
      getCity().then(response => {
        this.cityList = response?.data
      })
    },
    getList() {
      this.loading = true
      try {
        examinationList(this.queryParams)
          .then(response => {
            this.dataList = response.data.list
            this.total = response.data.count
          })
          .finally(() => {
            this.loading = false
          })
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮
    cancel() {
      this.visible = false
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    parentIdFormat(row) {
      return this.selectItemsLabel(this.parentIdOptions, row.parentId)
    },
    // 文件
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.consult_wz_id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      // this.reset()
      this.visible = true
      this.title = '添加'
    },
    handleUpdate(row) {
      this.reset()
      this.visible = true
      this.title = '修改'
      this.form = {
        id: row.id,
        name: row.name,
        type: row.type,
        subject: row.subject,
        public_range: row.public_range,
        province: row.province,
        status: row.status,
        is_free_public: row.is_free_public,
        description: row.description,
        ex_type: row.ex_type,
        cover: row.cover,
        examination_duration: row.examination_duration
      }
    },
    getNames(list = [], id) {
      const info = list.find(item => item.value === id) ?? {}
      return info.label ?? ''
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateExamination({
              ...this.form,
              examination_duration: Number(this.form.examination_duration)
            }).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.visible = false
                this.getList()
                this.form = {}
              } else {
                this.msgError(response.msg)
              }
            })
            return
          }
          this.form.teaching_point =
            this.form.teaching_point ?? this.deptOptions?.[0].id
          addExamination({
            ...this.form,
            examination_duration: Number(this.form.examination_duration)
          }).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.visible = false
              this.getList()
              this.form = {}
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.ids
      this.$confirm('是否确认删除该数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return deleteExamination({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() {})
    },
    handleRemove() {
      this.form.cover = ''
    },
    uploadSuccess(res, file) {
      this.form = {
        ...this.form,
        cover: res.data.full_path
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2.0
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2M!')
      }
      return !isJPG && isLt2M
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    }
  }
}
</script>
